-- UIGoldenPotBonus
-- Create by cheny3
-- 黄金罐奖励

require "game/ui/misc/UIIndicator"
require "game/ui/form/workshop/UIItemDesc"
require "game/ui/form/sky_city/UIAirShipSkillDesc"

--UIGoldenPotBonus继承自Layer
UIGoldenPotBonus = class("UIGoldenPotBonus", function()
    return cc.Layer:create();
end);

local sortBonus;

function UIGoldenPotBonus.create(campId)
    return UIGoldenPotBonus.new(campId);
end

-- 构造函数
function UIGoldenPotBonus:ctor(campId)
    self:setName("UIGoldenPotBonus");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/talent/TalentFruitBonus.csb");
    self:addChild(node);
    self.node = node;
    self.campId = campId;

    local CT = node:getChildByName("CT");

    local scrollview = CT:getChildByName("scrollview");
    local line1 = CT:getChildByName("line1");
    local line3 = CT:getChildByName("line3");
    scrollview:setVisible(false);
    line1:setVisible(false);
    line3:setVisible(false);

    scrollview = CT:getChildByName("scrollview2");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);
    self.oriHeight = self.scrollView:getInnerContainerSize().height;

    self:init();

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(1);

    -- 重绘
    self:redraw();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 适配
    self:resize();
end

-- 重绘
function UIGoldenPotBonus:redraw()
    local node = self.node;

    -- 更新奖励气泡
    self:updateBonusBubble();

    -- 标题
    local title1 = findChildByName(self.node, "CT/title1");
    local campName = CampM.query(self.campId, "name");
    title1:setString(campName);
    TextStyleM.setTitleStyle(title1);
    title1:setVisible(true);
    if not self.title1PosY then
        self.title1PosY = title1:getPositionY();
    end
    title1:setPositionY(self.title1PosY + 10);

    local record = table.deepcopy(ME.user.dbase:query("golden_pot_use_record", {}));
    local campRecord = record[self.campId] or {};
    -- 获得使用数量和当前领取进度
    local useNum = campRecord.use_num or 0;
    local progress = campRecord.progress or 0;
    local nextPorgerss = progress + 1 + self.campId * 100;
    local needNum = 0;

    if PetShopM.queryGoldenPotBonus(nextPorgerss) then
        needNum = PetShopM.queryGoldenPotBonus(nextPorgerss)["count"];
        useNum = math.min(useNum, PetShopM.getMaxBonusNum());
    else
        needNum = PetShopM.queryGoldenPotBonus(progress + self.campId * 100)["count"];
        -- 最多显示可领取等级上限
        useNum = math.min(useNum, needNum);
    end

    -- 副标题
    local title2 = findChildByName(self.node, "CT/title2");
    title2:setString(string.format(getLocStr("open_golden_pot"), useNum, needNum));
    title2:getVirtualRenderer():setHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER);
    TextStyleM.setSubheadStyle(title2);
    title2:setVisible(true);

    -- 阵营图标
    local icon = findChildByName(self.node, "CT/img");
    icon:loadTexture(getCampIconPath(self.campId));
    icon:setVisible(true);
end

-- 注册点击事件
function UIGoldenPotBonus:registerTouchEvent()
    -- 注册领取按钮点击事件
    local btnTakeBonus = findChildByName(self.node, "BT/take_bonus");
    local function onTakeBonusClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            local ret = PetShopM.canTakePotUseBonus(self.campId);
            if ret ~= true then
                -- TODO
                alert();
                -- 播放界面音效
                AudioM.playFx("slime_gain_failed");
                return;
            end

            Operation.cmd_take_golden_pot_use_bonus(self.campId);

            local progerss = (ME.user.dbase:query("golden_pot_use_record",
                {})[self.campId] or {})["progress"] or 0;
            if progerss > 0 then
                local id = progerss + 100 * self.campId;
                self:updateTakenFlag(id);

                self:jumpTo(id);
            end
        end
    end
    btnTakeBonus:addTouchEventListener(onTakeBonusClick);
    TextStyleM.setTextStyle(btnTakeBonus, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnTakeBonus:setTitleText(getLocStr("take_bonus"));

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UIGoldenPotBonus");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 注册事件处理回调函数
function UIGoldenPotBonus:registerEventCallback()
    -- 关注领取奖励的回调
    EventMgr.register("UIGoldenPotBonus", event.TAKE_GOLDEN_POT_BONUS, function(args)
        self:whenTakeFruitBonus(args);
        self:redraw();
    end);

    self:registerScriptHandler(function(ev)
        if ev == "enterTransitionFinish" then
            -- 默认显示最底部内容
            local scrollview = findChildByName(self.node, "CT/scrollview2");
            self:jumpTo(self.lastTaken);
        elseif ev == "exit" then
            EventMgr.removeAll("UIGoldenPotBonus");
        end
    end);
end

-- 初始化奖励
function UIGoldenPotBonus:initItem(node, bonusInfo, id)
    local bonus = bonusInfo[1];

    -- 图标
    local icon = findChildByName(node, "icon");

    local iconPath;
    local name;
    local num = bonus[3];
    local scale = 0.6;
    local offsetY = 0;

    -- 奖励名称
    local nameLabel = findChildByName(node, "name");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);

    -- 需求数量
    local numLabel = findChildByName(node, "num");
    local record = table.deepcopy(ME.user.dbase:query("golden_pot_use_record", {}));
    local campRecord = record[self.campId] or {};

    -- 获得使用数量和当前领取进度
    local useNum = campRecord.use_num or 0;
    local needNum = PetShopM.queryGoldenPotBonus(id)["count"];
    local numText = string.format(getLocStr("attrib_value_format"), useNum, needNum);
    TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    numLabel:setString(numText);
    self.isHonorDebris = false;

    if bonus[1] == 1 then
        -- 是道具， 获取道具图标
        iconPath = getItemIconPath(ItemM.query(bonus[2], "icon"));
        name = ItemM.query(bonus[2], "name");
        scale = 0.6;
        if ItemM.query(bonus[2], "group") == 17 then
            node.isHonorDebris = true;
            scale = 0.5;
        end
    elseif bonus[1] == 2 then
        name = FieldsM.query(bonus[2], "name");
        scale = 1;
        -- 是属性
        if "gem" == bonus[2] then
            iconPath = getLargeAttribIconPath("gem_large");
        else
            iconPath = getLargeAttribIconPath(bonus[2]);
            scale = 0.6;
        end
    elseif bonus[1] == 6 then
        -- 秘宝
        local classId = tonumber(bonus[2]);
        local fileName = SkyShipSkillM.query(classId, "icon");
        iconPath = getAirShipSkillIconPath(tostring(fileName));
        name = SkyShipSkillM.query(classId, "name");
        scale = 0.6;
    end
    icon:loadTexture(iconPath);
    icon:setScale(scale);
    icon:setPositionY(icon:getPositionY()+offsetY);

    local bg = findChildByName(node, "touch_bg");
    bg:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("workshop_material");
            showBonusDesc(bonus);
        end
    end);

    if num > 1 then
        nameLabel:setString(string.format("%s×%s", name, num));
    else
        nameLabel:setString(name);
    end

    if bonus[1] == 2 then
       nameLabel:setString(string.format("%s+%s", name, num));
    end
end

-- 更新是否已领取的标识
function UIGoldenPotBonus:updateTakenFlag(id)
    local node = self.itemIcons[id];
    local isTaken = SkyScrapBonusM.isTaken(id);
    if isTaken then
        self.lastTaken = id;
    end

    -- 可领取光效
    local light = findChildByName(node, "light");

    local nameLabel = findChildByName(node, "name");
    local numLabel = findChildByName(node, "num");
    local mengban  = findChildByName(node, "taken_image");
    local itemIcon = findChildByName(node, "icon");

    -- 是否已经领取
    local isTake = PetShopM.isTakeGoldenPotUseBonus(id);
    if PetShopM.isTakeGoldenPotUseBonus(id) then
        -- 已领取，名字置灰，添加一层黄色蒙版
        mengban:setVisible(true);
        light:setVisible(false);
        itemIcon:stopAllActions();

        TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GRAY);

        TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GRAY);
        if getLang() == "zh" or getLang() == "tw" then
            numLabel:setString(getLocStr("has_received"));
        else
            numLabel:setString("");
        end
    elseif PetShopM.canTakePotUseBonusById(id) then
        -- 可以领取
        TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GREEN);
        TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GREEN);
        if getLang() == "zh" or getLang() == "tw" then
            numLabel:setString(getLocStr("can_be_taken"));
        end

        light:setVisible(true);
        local rotateForever = cc.RepeatForever:create(cc.RotateBy:create(30, 360));
        light:runAction(rotateForever);

        local bonus = PetShopM.queryGoldenPotBonus(id)["bonus"];
        if node.isHonorDebris then
            -- 碎片
            playBubbleAnima2(itemIcon, false, 0.5);
        elseif bonus[2] == "gem" then
            playBubbleAnima2(itemIcon, false, 1);
        else
            playBubbleAnima2(itemIcon, false, 0.6);
        end
    else
        -- 不可领取
        light:setVisible(false);
    end
end

-- 移动中心
function UIGoldenPotBonus:jumpTo(id)
    id = iif(id==nil, 1, id);

    id = id - 3;

    local scrollview = findChildByName(self.node, "CT/scrollview2");
    local percent = id * 100 / self.totalCount;
    if percent < 0 then
        percent = 0;
    end

    scrollview:jumpToPercentVertical(percent);
end

-- 排序
function sortBonus(item1, item2)
    return item1.id < item2.id;
end

-- 初始化奖励列表
function UIGoldenPotBonus:init()
    local scrollview = findChildByName(self.node, "CT/scrollview2");
    scrollview:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/talent/FruitBonusItem.csb");
    local widget = replaceNodeWithWidget(itemNode);

    -- 获取奖励列表
    local bonusList = {};
    for _, info in pairs(PetShopM.queryGoldenPotBonus()) do
        if info.camp_id == self.campId then
            table.insert(bonusList, info);
        end
    end

    -- 排序一下
    table.sort(bonusList, sortBonus);

    -- 左边距
    local leftMargin = 1;

    -- 行间距
    local gap = 0;
    local widgetHeight = 61;

    local totalNum = 0;
    for k,v in pairs(bonusList) do
        totalNum = totalNum + 1;
    end
    self.totalCount = totalNum;

    local startHeight = 0;

    -- 计算总高度
    local totalHeight = math.max(totalNum * (widgetHeight + gap), scrollview:getInnerContainerSize().height);
    if totalHeight < scrollview:getInnerContainerSize().height then
        -- startHeight = scrollview:getInnerContainerSize().height - totalHeight;
    end

    -- 绘制顶部横线
    self:redrawTopLines(totalHeight);

    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width, totalHeight));

    self.itemIcons = {};
    local i = 0;
    for _, info in pairs(bonusList) do
        local id = info.id;
        local bonus = PetShopM.queryGoldenPotBonus(id)["bonus"];

        local child = widget:clone();
        local x = leftMargin;
        local y = i * -60 + totalHeight - 80;
        child:setPositionX(x);
        child:setPositionY(y);

        self.itemIcons[id] = child;

        -- 初始化奖励
        child:setTag(i);
        self:initItem(child, {bonus}, id);
        self:updateTakenFlag(id);

        scrollview:addChild(child);
        i = i + 1;
    end

    if totalHeight > self.oriHeight then
        UIIndicator.attach(scrollview);
    end
end

-- 绘制Top横线
-- 为了防止滚动穿帮，先这么处理
function UIGoldenPotBonus:redrawTopLines(totalHeight)
    local lineNode = cc.CSLoader:createNode("layout/talent/FruitBonusItem.csb");
    local widget = replaceNodeWithWidget(lineNode);

    local child = widget:clone();
    local line = child:getChildByName("line");
    for _, node in pairs(child:getChildren()) do
        node:setVisible(false);
    end
    line:setVisible(true);
    child:setAnchorPoint(cc.p(0.5, 0.5));
    child:setPositionX(1);
    child:setPositionY(totalHeight - 25);

    self.scrollView:addChild(child);
end

-- 适配
function UIGoldenPotBonus:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 领取奖励的回调
function UIGoldenPotBonus:whenTakeFruitBonus(args)
    local bonus = args.bonus;

    if bonus ~= nil and #bonus > 0 then
        showBonusNotifyForm(getLocStr("achive_award"), {bonus});
    end
end

-- 更新可领取奖励泡泡
function UIGoldenPotBonus:updateBonusBubble()
    local hintNode = findChildByName(self.node, "BT/take_bonus/hint");

    -- 如果可领取奖励为0，则领取奖按钮置灰不可用
    local canGetNum = PetShopM.takePotUseBonusNum(self.campId);
    checkBlueBubbleStatus(hintNode, canGetNum);

    local btnTakeBonus = findChildByName(self.node, "BT/take_bonus");
    btnTakeBonus:setVisible(true);
    if canGetNum < 1 then
        btnTakeBonus:setTouchEnabled(false);
        btnTakeBonus:setBright(false);
    end
end
